// pages/Shop/Shop.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    activeKey: 0,
    //sortsWithDetails: [],
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    sortsWithDetails: [{
        "Id": 1,
        "Name": "档口1",
        "Details": [{
            "Id": 1,
            "Name": "红烧肉盖饭",
            "Price": 10,
            "ImageUrl": "http://example.com/image1.jpg",
            "DateTime": "2023-07-01",
            "Sales": 200
          },
          {
            "Id": 2,
            "Name": "鱼香肉丝盖饭",
            "Price": 200,
            "ImageUrl": "http://example.com/image2.jpg",
            "DateTime": "2023-07-02",
            "Sales": 150
          }
        ]
      },
      {
        "Id": 2,
        "Name": "档口2",
        "Details": [{
          "Id": 3,
          "Name": "详情3",
          "Price": 150,
          "ImageUrl": "http://example.com/image3.jpg", // 我假设了图片URL，因为原始数据中并未提供  
          "DateTime": "2023-07-03", // 我假设了日期，因为原始数据中并未提供  
          "Sales": 100 // 我假设了销量，因为原始数据中并未提供  
        }]
      },
      {
        "Id": 3,
        "Name": "档口3",
        "Details": [{
          "Id": 21,
          "Name": "详情3",
          "Price": 150,
          "ImageUrl": "http://example.com/image3.jpg", // 我假设了图片URL，因为原始数据中并未提供  
          "DateTime": "2023-07-03", // 我假设了日期，因为原始数据中并未提供  
          "Sales": 100 // 我假设了销量，因为原始数据中并未提供  
        }]
      }
    ],
    selectedSortIndex: 0,
    indexId: 0,
    toTitle: "title-0",
    scrollTop: 0,
    top: [],
    totalPrice: 0, //选中商品总价格
    totalNum: 0, //选中商品数量
    cartList: [], //选中商品列表
    // 购物车动画
    animationData: {},
    animationMask: {},
    maskVisual: "hidden",
    maskFlag: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    let height=0;
    let list = [];
    wx.request({
      url: 'https://localhost:7264/api/Details/DetailList',
      method: "GET",
      success(res) {
        // 将API响应数据转换为适用于小程序页面的格式
        var sortsWithDetails = res.data.$values.map(item => {
          // 对Details数组内的数据进行进一步处理
          var details = item.Commoditys.$values.map(commodityItem => {
           
            return {
              // 在这里定义Details字段的格式
              // 例如，如果Details包含Id和Description字段：
              Id: commodityItem.Id,
              Name: commodityItem.Name,
              Price: commodityItem.Price,
              ImageUrl: commodityItem.ImageUrl,
              DateTime: commodityItem.DateTime,
              Sales: commodityItem.Sales,
              CupTypeOptions: commodityItem.CupTypeOptions.$values,
              TemperatureOptions: commodityItem.TemperatureOptions.$values,
              SugarOptions: commodityItem.SugarOptions.$values,
              IceOptions: commodityItem.IceOptions.$values,
            };
          });
          height+=(details.length*80)
          return {
            top:height-(details.length*80),
            bottom:height,
            Id: item.Id,
            Name: item.Name,
            Details: details,
          };
          
        });
        // 更新页面数据
        that.setData({
          sortsWithDetails: sortsWithDetails,
        });
        // console.log(res.data);
        // console.log(that.data.sortsWithDetails);
      }
    });
  },
  onShow() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        //唯一标识（其它设置不同的整数）  
        selected: 1
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  goToDetail(event) {
    // 获取点击的商品ID
    const productId = event.currentTarget.dataset.productId;
    console.log('接收到的商品ID:', event.currentTarget.dataset.productId);
    // 跳转到详情页并传递商品ID
    wx.navigateTo({
      url: '/pages/Detail/Detail?id=' + productId,
    });
  },
  toggleDetails: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedSortIndex: index,
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  sortDetails: function (criterion) {
    const details = this.data.sortsWithDetails[this.data.selectedSortIndex].Details;
    switch (criterion) {
      case 'sales':
        details.sort((a, b) => b.Sales - a.Sales); // Sort by sales in descending order
        break;
      case 'time':
        details.sort((a, b) => new Date(b.DateTime) - new Date(a.DateTime)); // Sort by time in descending order
        break;
      case 'price':
        details.sort((a, b) => a.Price - b.Price); // Sort by price in ascending order
        break;
      default:
        break;
    }
    this.setData({
      ['sortsWithDetails[' + this.data.selectedSortIndex + '].Details']: details,
    });
  },

  // Function to change the active tab and trigger sorting
  onChange: function (event) {
    const active = event.detail.name;
    this.setData({
      active
    });
    const criterion = active === 0 ? 'sales' : active === 1 ? 'time' : 'price'; // Map tab index to sorting criterion
    this.sortDetails(criterion);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  inputChange: function (e) {
    this.setData({
      searchInput: e.detail.value
    })
  },

  search: function () {
    // 这里可以编写搜索逻辑，比如调用接口获取搜索结果等  
    console.log('搜索内容：' + this.data.searchInput)
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      MainCur: e.currentTarget.dataset.id,
      VerticalNavTop: (e.currentTarget.dataset.id-1) *80
    })
    console.log(this.data)
  },

  
  VerticalMain(e) {
    let that = this;
    let list = this.data.sortsWithDetails;
    
    let tabHeight = 0;
    if (this.data.load) {
      for (let i = 0; i < list.length; i++) {
        let view = wx.createSelectorQuery().select("#main-" + list[i].Id);
        console.log(list[i].Id);
        view.fields({
          size: true
        }, data => {
          list[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          list[i].bottom = tabHeight;     
        }).exec();
      }
      that.setData({
        load: false,
        list: list
      })
    }
    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < list.length; i++) {
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
        that.setData({
          VerticalNavTop: (list[i].Id - 1) *80,
          TabCur: list[i].Id-1
        })
        return false
      }
    }
  }
})